const express = require('express')
const fs = require('fs');
const path = require("path");
const app = express()
const resolve = (file) => path.resolve(__dirname, file);
const { createBundleRenderer } = require('vue-server-renderer')


// 获得一个createBundleRenderer
const serverBundle = require('../dist/server/vue-ssr-server-bundle.json')
const clientManifest = require('../dist/client/vue-ssr-client-manifest.json')
const template = fs.readFileSync(path.resolve(__dirname, "../public/index.template.html"), "utf-8")

const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false, // 推荐
  template, // （可选）页面模板
  clientManifest
})

// 开放dist目录
app.use(express.static(resolve("../dist/client"), {index:false}))


function renderToString(context) {
    return new Promise((resolve, reject) => {
        renderer.renderToString(context, (err, html) => {
        err ? reject(err) : resolve(html);
        });
    });
}


// 添加一个中间件来处理所有请求
app.get('*', async (req, res)=>{
    try {
        const context = { 
            url: req.url,
            title: 'srr test'
        }
        let html = await renderToString(context)
        console.log(html)
        res.send(html)
    } catch (error){
        // res.status(500).send("服务器内部错误")
        res.status(500).send("服务器内部错误")
    }
})

app.listen(3000, ()=>{
    console.log('服务器启动成功')
})